package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptiion.LyException;
import com.leyou.common.utils.UploadFileUtils;
import com.leyou.common.vo.UploadFileVO;
import com.leyou.upload.config.UploadProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @ClassName UploadService
 * @Date 2019/2/12 13:30
 */
@Service
@Slf4j
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {

   /* @Autowired
    private FastFileStorageClient storageClient;
    */

   @Autowired
    UploadProperties prop;
   // private  static  final String BASEURL="http://image.leyou.com:8881/upload";
    
    public String uploadImage(MultipartFile file) {
        try {
            //校验文件
            if (!prop.getAllowTypes().contains(file.getContentType())) {
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image ==null) {
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //上传到FastDFS
           /* String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
           */
            UploadFileVO uploadFileVO=null;

              uploadFileVO = UploadFileUtils.uploadImageOne(file);
            String fileUrl= uploadFileVO.getProjectFileUrl();
            String url = prop.getBaseUrl() + uploadFileVO.getProjectFileUrl();
            log.info("路径---------"+url);
            return url;
        } catch (Exception e) {
            log.error("文件上传失败!", e);
            throw new LyException(ExceptionEnum.UPLOAD_FILE_ERROR);
        }
    }
}
